package development;

import java.io.IOException;
import java.util.Hashtable;

import javax.microedition.lcdui.Graphics;

import state.Alert;
import state.GameForm;
import state.Key;
import state.bean.File;
import state.font.FontManager;
import state.font.ImageFont;
import state.util.Color;

public class FrmListFile extends GameForm {
  
  private final int DX = 20;
  
  private final int DY = 40;
  
  private final int DESCRIPTION_DX = 180;
  
  private final int ROW_DIS = 20;
  
  private File[] files;
  
  private File parent;
  
  private ImageFont text11;
  
  private int currentRow;
  
  private static GameForm singleton;
  
  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmListFile();
    }
    return singleton;
  }
  
  public void init(Hashtable parameters) {
    manager.setBackGroundColor(Color.BLACK_CODE);
    text11 = FontManager.getFont(FontManager.FONT_SIZE_11);
    currentRow = 0;
    
    parent = null;
    try {
      files = new File[] {File.getRoot(File.READ)};
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  
  public void draw(Graphics g) {
    if (parent != null) {
      text11.drawString(g, "...", Color.WHITE_CODE, DX, DY - ROW_DIS, Constants.TOP_LEFT_ANCHOR);
    }
    
    for (int i = 0; i < files.length; i++) {
      text11.drawString(g, files[i].getName(), Color.WHITE_CODE, DX, DY + i * ROW_DIS, Constants.TOP_LEFT_ANCHOR);
      
      if (files[i].isDirectory()) {
        text11.drawString(g, "[Folder]", Color.WHITE_CODE, DESCRIPTION_DX, DY + i * ROW_DIS, Constants.TOP_LEFT_ANCHOR);
      } else {
        text11.drawString(g, "[File]", Color.WHITE_CODE, DESCRIPTION_DX, DY + i * ROW_DIS, Constants.TOP_LEFT_ANCHOR);
      }
    }
    
    // Draw border for current row
    g.setColor(Color.WHITE_CODE);
    g.drawRect(DX - 2, DY + (currentRow - 1) * ROW_DIS, 200, 20);
  }
  
  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.DOWN:
      currentRow = ++currentRow > files.length + 1 ? files.length + 1 : currentRow;
      break;
    case Key.UP:
      currentRow = --currentRow < 0 ? 0 : currentRow;
      break;
    case Key.FIRE:
      if ((currentRow == 0) && (parent != null)) {
        try {
          files = parent.list();
          parent = files[0].getParent();
        } catch (IOException e) {
          e.printStackTrace();
        }
      } else if (files[currentRow - 1].isDirectory()) {
        try {
          parent = files[currentRow - 1];
          files = files[currentRow - 1].list();
        } catch (IOException e) {
          e.printStackTrace();
        }
      } else {
        Global.alert.showAlert(this, Alert.OK_TYPE, "You opened file: " + files[currentRow - 1].getName());
      }
      break;
    }
  }
  
}
